import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import '../../controllers/record_controller.dart';
import '../../core/theme/app_colors.dart';
import '../../core/theme/app_text_styles.dart';
import '../../core/constants/app_constants.dart';
import '../../data/models/emotion_record.dart';
import '../widgets/emotion_selector_widget.dart';
import '../layouts/main_layout.dart';

/// 记录页面 - 用于创建和编辑情绪记录
/// Record Page - For creating and editing emotion records
class RecordPage extends GetView<RecordController> {
  const RecordPage({super.key});

  @override
  Widget build(BuildContext context) {
    return MainLayout(
       currentIndex: 0, // 设置为有效索引 / Set to valid index
       showBottomNavigation: false, // 隐藏底部导航栏 / Hide bottom navigation
       appBarTitle: '记录情绪',
       appBarActions: [
        // 保存按钮 / Save button
        Obx(() => TextButton(
            onPressed: controller.canSave ? controller.saveRecord : null,
            child: Text(
              '保存',
              style: TextStyle(
                color: controller.canSave 
                  ? AppColors.primary 
                  : AppColors.textSecondary,
            ),
          ),
        )),
      ],
      child: Obx(() => controller.isLoading.value
          ? const Center(child: CircularProgressIndicator())
          : SingleChildScrollView(
              padding: const EdgeInsets.all(AppConstants.paddingLarge),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 错误信息显示 / Error message display
                  Obx(() {
                    if (controller.errorMessage.value.isNotEmpty) {
                      return Container(
                        width: double.infinity,
                        padding: const EdgeInsets.all(AppConstants.paddingMedium),
                        margin: const EdgeInsets.only(bottom: AppConstants.spacingLarge),
                        decoration: BoxDecoration(
                          color: AppColors.error.withOpacity(0.1),
                          borderRadius: BorderRadius.circular(AppConstants.radiusSmall),
                          border: Border.all(color: AppColors.error.withOpacity(0.3)),
                        ),
                        child: Row(
                          children: [
                            Icon(
                              Icons.error_outline,
                              color: AppColors.error,
                              size: AppConstants.iconSizeSmall,
                            ),
                            const SizedBox(width: AppConstants.spacingSmall),
                            Expanded(
                              child: Text(
                                controller.errorMessage.value,
                                style: AppTextStyles.bodyMedium.copyWith(
                                  color: AppColors.error,
                                ),
                              ),
                            ),
                            IconButton(
                              onPressed: controller.clearError,
                              icon: Icon(
                                Icons.close,
                                color: AppColors.error,
                                size: AppConstants.iconSizeSmall,
                              ),
                            ),
                          ],
                        ),
                      );
                    }
                    return const SizedBox.shrink();
                  }),
                  
                  _buildRecordForm(context),
                ],
              ),
            )),
    );
  }

  /// 构建记录表单
  /// Build record form
  Widget _buildRecordForm(BuildContext context) {
    return SingleChildScrollView(
      padding: EdgeInsets.all(16.w),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 情绪选择区域 / Emotion selection area
          _buildEmotionSection(),
          SizedBox(height: 24.h),
          
          // 日记编辑区域 / Diary editing area
          _buildDiarySection(),
          SizedBox(height: 24.h),
          
          // 多媒体上传区域 / Media upload area
          _buildMediaSection(),
          SizedBox(height: 24.h),
          
          // 标签区域 / Tags area
          _buildTagsSection(),
          SizedBox(height: 32.h),
        ],
      ),
    );
  }

  /// 构建情绪选择区域
  /// Build emotion selection section
  Widget _buildEmotionSection() {
    return Container(
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        color: AppColors.surface,
        borderRadius: BorderRadius.circular(12.r),
        boxShadow: AppConstants.shadowSoft,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '今天的心情如何？',
            style: AppTextStyles.titleMedium.copyWith(
              color: AppColors.textPrimary,
              fontSize: 18.sp,
            ),
          ),
          SizedBox(height: 16.h),
          EmotionSelectorWidget(
                  initialEmotionType: controller.selectedEmotion.value?.value,
                  initialIntensity: controller.selectedIntensity.round(),
                  onEmotionSelected: (String emotion, int intensity) {
                    try {
                      // 将String转换为EmotionType / Convert String to EmotionType
                      final emotionType = EmotionType.fromString(emotion);
                      controller.setSelectedEmotion(emotionType);
                      controller.setEmotionIntensity(intensity.toDouble());
                    } catch (e) {
                      // 处理转换错误，使用默认值 / Handle conversion error with default value
                      print('Error converting emotion type: $e');
                      controller.setSelectedEmotion(EmotionType.calm);
                      controller.setEmotionIntensity(intensity.toDouble());
                    }
                  },
                ),
        ],
      ),
    );
  }

  /// 构建日记编辑区域
  /// Build diary editing section
  Widget _buildDiarySection() {
    return Container(
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        color: AppColors.surface,
        borderRadius: BorderRadius.circular(12.r),
        boxShadow: AppConstants.shadowSoft,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '记录今天的想法',
            style: AppTextStyles.titleMedium.copyWith(
              color: AppColors.textPrimary,
              fontSize: 18.sp,
            ),
          ),
          SizedBox(height: 16.h),
          
          // 日记输入框 / Diary input field
          TextField(
            controller: controller.diaryController,
            maxLines: 8,
            maxLength: AppConstants.maxDiaryLength,
            decoration: InputDecoration(
              hintText: '分享你的感受、想法或今天发生的事情...',
              hintStyle: AppTextStyles.bodyMedium.copyWith(
                color: AppColors.textSecondary,
              ),
              border: OutlineInputBorder(
                borderRadius: BorderRadius.circular(AppConstants.radiusSmall),
                borderSide: BorderSide(color: AppColors.border),
              ),
              enabledBorder: OutlineInputBorder(
                borderRadius: BorderRadius.circular(AppConstants.radiusSmall),
                borderSide: BorderSide(color: AppColors.border),
              ),
              focusedBorder: OutlineInputBorder(
                borderRadius: BorderRadius.circular(AppConstants.radiusSmall),
                borderSide: BorderSide(color: AppColors.primary, width: 2),
              ),
              filled: true,
              fillColor: AppColors.background,
              contentPadding: const EdgeInsets.all(AppConstants.paddingMedium),
            ),
            style: AppTextStyles.bodyMedium,
            onChanged: controller.setDiaryContent,
          ),
          
          // 字数统计 / Character count
          const SizedBox(height: AppConstants.spacingSmall),
          Obx(() => Align(
            alignment: Alignment.centerRight,
            child: Text(
              '${controller.diaryContent.value.length}/${AppConstants.maxDiaryLength}',
              style: AppTextStyles.bodySmall.copyWith(
                color: controller.diaryContent.value.length > AppConstants.maxDiaryLength * 0.9
                    ? AppColors.warning
                    : AppColors.textSecondary,
              ),
            ),
          )),
        ],
      ),
    );
  }

  /// 构建多媒体上传区域
  /// Build media upload section
  Widget _buildMediaSection() {
    return Container(
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        color: AppColors.surface,
        borderRadius: BorderRadius.circular(12.r),
        boxShadow: AppConstants.shadowSoft,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '添加照片或录音',
            style: AppTextStyles.titleMedium.copyWith(
              color: AppColors.textPrimary,
              fontSize: 18.sp,
            ),
          ),
          SizedBox(height: 16.h),
          
          // 媒体操作按钮 / Media action buttons
          Row(
            children: [
              // 拍照按钮 / Camera button
              Expanded(
                child: _buildMediaButton(
                  icon: Icons.camera_alt,
                  label: '拍照',
                  onTap: () => controller.takePhoto(),
                ),
              ),
              const SizedBox(width: AppConstants.spacingMedium),
              
              // 相册按钮 / Gallery button
              Expanded(
                child: _buildMediaButton(
                  icon: Icons.photo_library,
                  label: '相册',
                  onTap: () => controller.pickImage(),
                ),
              ),
              const SizedBox(width: AppConstants.spacingMedium),
              
              // 录音按钮 / Recording button
              Expanded(
                child: Obx(() => _buildMediaButton(
                  icon: controller.isRecording.value ? Icons.stop : Icons.mic,
                  label: controller.isRecording.value ? '停止' : '录音',
                  onTap: controller.isRecording.value 
                      ? controller.stopRecording 
                      : controller.startRecording,
                  color: controller.isRecording.value ? AppColors.error : null,
                )),
              ),
            ],
          ),
          
          // 已选择的媒体文件 / Selected media files
          const SizedBox(height: AppConstants.spacingMedium),
          Obx(() => _buildSelectedMedia()),
        ],
      ),
    );
  }

  /// 构建媒体按钮
  /// Build media button
  Widget _buildMediaButton({
    required IconData icon,
    required String label,
    required VoidCallback onTap,
    Color? color,
  }) {
    return InkWell(
      onTap: onTap,
      borderRadius: BorderRadius.circular(AppConstants.radiusSmall),
      child: Container(
        padding: const EdgeInsets.symmetric(
          vertical: AppConstants.paddingMedium,
          horizontal: AppConstants.paddingSmall,
        ),
        decoration: BoxDecoration(
          color: AppColors.background,
          borderRadius: BorderRadius.circular(AppConstants.radiusSmall),
          border: Border.all(color: AppColors.border),
        ),
        child: Column(
          children: [
            Icon(
              icon,
              color: color ?? AppColors.primary,
              size: AppConstants.iconSizeMedium,
            ),
            const SizedBox(height: AppConstants.spacingSmall),
            Text(
              label,
              style: AppTextStyles.bodySmall.copyWith(
                color: color ?? AppColors.textPrimary,
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建已选择的媒体文件
  /// Build selected media files
  Widget _buildSelectedMedia() {
    if (controller.selectedImages.isEmpty && controller.audioPath.value.isEmpty) {
      return const SizedBox.shrink();
    }

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 图片列表 / Image list
        if (controller.selectedImages.isNotEmpty) ...[
          Text(
            '已选择的图片',
            style: AppTextStyles.bodyMedium.copyWith(
              color: AppColors.textSecondary,
            ),
          ),
          const SizedBox(height: AppConstants.spacingSmall),
          SizedBox(
            height: 80,
            child: ListView.builder(
              scrollDirection: Axis.horizontal,
              itemCount: controller.selectedImages.length,
              itemBuilder: (context, index) {
                final imageFile = controller.selectedImages[index];
                return Container(
                  margin: const EdgeInsets.only(right: AppConstants.spacingSmall),
                  child: Stack(
                    children: [
                      ClipRRect(
                        borderRadius: BorderRadius.circular(AppConstants.radiusSmall),
                        child: Image.file(
                          imageFile,
                          width: 80,
                          height: 80,
                          fit: BoxFit.cover,
                        ),
                      ),
                      Positioned(
                        top: 4,
                        right: 4,
                        child: GestureDetector(
                          onTap: () => controller.removeImage(index),
                          child: Container(
                            padding: const EdgeInsets.all(2),
                            decoration: BoxDecoration(
                              color: AppColors.error,
                              shape: BoxShape.circle,
                            ),
                            child: Icon(
                              Icons.close,
                              size: 16,
                              color: AppColors.onError,
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                );
              },
            ),
          ),
        ],
        
        // 录音文件 / Audio file
        if (controller.audioPath.value.isNotEmpty) ...[
          if (controller.selectedImages.isNotEmpty) 
            const SizedBox(height: AppConstants.spacingMedium),
          Text(
            '录音文件',
            style: AppTextStyles.bodyMedium.copyWith(
              color: AppColors.textSecondary,
            ),
          ),
          const SizedBox(height: AppConstants.spacingSmall),
          Container(
            padding: const EdgeInsets.all(AppConstants.paddingMedium),
            decoration: BoxDecoration(
              color: AppColors.background,
              borderRadius: BorderRadius.circular(AppConstants.radiusSmall),
              border: Border.all(color: AppColors.border),
            ),
            child: Row(
              children: [
                Icon(
                  Icons.audiotrack,
                  color: AppColors.primary,
                  size: AppConstants.iconSizeSmall,
                ),
                const SizedBox(width: AppConstants.spacingSmall),
                Expanded(
                  child: Text(
                    '录音文件.m4a',
                    style: AppTextStyles.bodyMedium,
                  ),
                ),
                IconButton(
                  onPressed: controller.removeAudio,
                  icon: Icon(
                    Icons.delete,
                    color: AppColors.error,
                    size: AppConstants.iconSizeSmall,
                  ),
                ),
              ],
            ),
          ),
        ],
      ],
    );
  }

  /// 构建标签区域
  /// Build tags section
  Widget _buildTagsSection() {
    return Container(
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        color: AppColors.surface,
        borderRadius: BorderRadius.circular(12.r),
        boxShadow: AppConstants.shadowSoft,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '添加标签',
            style: AppTextStyles.titleMedium.copyWith(
              color: AppColors.textPrimary,
              fontSize: 18.sp,
            ),
          ),
          SizedBox(height: 16.h),
          
          // 标签输入框 / Tag input field
          Row(
            children: [
              Expanded(
                child: TextField(
                  controller: controller.tagController,
                  decoration: InputDecoration(
                    hintText: '输入标签名称',
                    hintStyle: AppTextStyles.bodyMedium.copyWith(
                      color: AppColors.textSecondary,
                    ),
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(AppConstants.radiusSmall),
                      borderSide: BorderSide(color: AppColors.border),
                    ),
                    enabledBorder: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(AppConstants.radiusSmall),
                      borderSide: BorderSide(color: AppColors.border),
                    ),
                    focusedBorder: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(AppConstants.radiusSmall),
                      borderSide: BorderSide(color: AppColors.primary, width: 2),
                    ),
                    filled: true,
                    fillColor: AppColors.background,
                    contentPadding: const EdgeInsets.symmetric(
                      horizontal: AppConstants.paddingMedium,
                      vertical: AppConstants.paddingSmall,
                    ),
                  ),
                  style: AppTextStyles.bodyMedium,
                  onSubmitted: (value) {
                    if (value.trim().isNotEmpty) {
                      controller.addTag(value.trim());
                      controller.tagController.clear();
                    }
                  },
                ),
              ),
              const SizedBox(width: AppConstants.spacingSmall),
              IconButton(
                onPressed: () {
                  final tag = controller.tagController.text.trim();
                  if (tag.isNotEmpty) {
                    controller.addTag(tag);
                    controller.tagController.clear();
                  }
                },
                icon: Icon(
                  Icons.add,
                  color: AppColors.primary,
                ),
              ),
            ],
          ),
          
          // 已添加的标签 / Added tags
          const SizedBox(height: AppConstants.spacingMedium),
          Obx(() => _buildTagsList()),
        ],
      ),
    );
  }

  /// 构建标签列表
  /// Build tags list
  Widget _buildTagsList() {
    if (controller.tags.isEmpty) {
      return Text(
        '暂无标签',
        style: AppTextStyles.bodySmall.copyWith(
          color: AppColors.textSecondary,
        ),
      );
    }

    return Wrap(
      spacing: AppConstants.spacingSmall,
      runSpacing: AppConstants.spacingSmall,
      children: controller.tags.map((tag) {
        return Container(
          padding: const EdgeInsets.symmetric(
            horizontal: AppConstants.paddingMedium,
            vertical: AppConstants.paddingSmall,
          ),
          decoration: BoxDecoration(
            color: AppColors.primary.withOpacity(0.1),
            borderRadius: BorderRadius.circular(AppConstants.radiusLarge),
            border: Border.all(color: AppColors.primary.withOpacity(0.3)),
          ),
          child: Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              Text(
                tag,
                style: AppTextStyles.bodySmall.copyWith(
                  color: AppColors.primary,
                ),
              ),
              const SizedBox(width: AppConstants.spacingSmall),
              GestureDetector(
                onTap: () => controller.removeTag(tag),
                child: Icon(
                  Icons.close,
                  size: 16,
                  color: AppColors.primary,
                ),
              ),
            ],
          ),
        );
      }).toList(),
    );
  }
}